package com.chinastock.log;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * @author zhangfan.it
 * @date 2021/1/22
 */
@Component
@Order(Filters.PERF_LOG)
public class PerfLogFilter implements WebFilter {
    @Value("${performance.log.switch:true}")
    private boolean isOn;

    private static final Logger log = LoggerFactory.getLogger(LogName.PERFORMANCE);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        if (!isOn) {
            return chain.filter(exchange);
        }

        long start = System.currentTimeMillis();
        return chain.filter(exchange).doOnTerminate(() -> {
            long end = System.currentTimeMillis();
            long timeInterval = end - start;
            log.info("request processing finished in " + timeInterval + " (ms), at " + end);
        });
    }
}
